package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.IntegrationCashCouponWallet;
import com.rockcent.mall.lib.domain.IntegrationChannel;
import com.rockcent.mall.lib.domain.MallCashCoupon;
import com.rockcent.mall.lib.domain.enumclass.CashCouponStatus;
import com.rockcent.mall.lib.dto.MallCashCouponDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.IntegrationChannelRepository;
import com.rockcent.service.MallCashCouponSrv;
import com.rockcent.service.IntegrationCashCouponWalletSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

/**
 * M端现金券管理
 * Created by zhangjh on 2016/12/19.
 */
@RestController
public class MallCashCouponController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(MallCashCouponController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private MallCashCouponSrv mallCashCouponSrvImpl;

    @Autowired
    private IntegrationCashCouponWalletSrv integrationCashCouponWalletSrv;

    @Autowired
    private IntegrationChannelRepository integrationChannelRepository;

    /**
     * @api {post} /mall/integration/cash/save M端 新增现金券
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} faceValue <code>必须参数</code> 面额
     * @apiParam {Long} quantity <code>必须参数</code> 数量
     * @apiParam {Long} name <code>必须参数</code> 现金券名称
     * @apiParam {Long} picUrl <code>必须参数</code> 图片
     * @apiParam {String} status <code>必选</code> WAIT_ISSUE-保存从草稿，ISSUED-直接发放
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_SAVE, method = RequestMethod.POST)
    @Transactional
    public JsonResult addInfo(@RequestBody MallCashCouponDto vo, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (vo == null) {
                jsonResult.errorParam("现金券信息为空", log);
                return;
            }
            if (vo.getFaceValue() == null) {
                jsonResult.errorParam("面额为空", log);
                return;
            }
            if (vo.getQuantity() == null) {
                jsonResult.errorParam("发放总量为空", log);
                return;
            }
            if (vo.getName() == null) {
                jsonResult.errorParam("名称为空", log);
                return;
            }
            if (vo.getPicUrl() == null) {
                jsonResult.errorParam("图片地址为空", log);
                return;
            }
            if (vo.getStatus() == null) {
                jsonResult.errorParam("新建现金券状态为空", log);
                return;
            }
            String type = vo.getStatus();
            CashCouponStatus status = CashCouponStatus.valueOf(type);
            if (status == null || (status != CashCouponStatus.WAIT_ISSUE && status != CashCouponStatus.ISSUED)) {
                jsonResult.errorParam("新建现金券状态值错误", log);
                return;
            }

            MallCashCoupon mallCashCoupon =mallCashCouponSrvImpl.save(vo, mallId);

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /mall/integration/cash/update M端 修改现金券
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必须参数</code>  现金券id
     * @apiParam {Long} faceValue <code>必须参数</code> 面额
     * @apiParam {Long} quantity <code>必须参数</code> 数量
     * @apiParam {Long} name <code>必须参数</code> 现金券名称
     * @apiParam {Long} picUrl <code>必须参数</code> 图片
     * @apiParam {String} status <code>必选</code> WAIT_ISSUE-保存从草稿，ISSUED-直接发放
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_UPDATE, method = RequestMethod.PUT)
    @Transactional
    public JsonResult updateInfo(@RequestBody MallCashCouponDto vo, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (vo == null) {
                jsonResult.errorParam("现金券信息为空", log);
                return;
            }

            if (vo.getId() == null) {
                jsonResult.errorParam("现金券id为空", log);
                return;
            }
            if (vo.getName() == null) {
                jsonResult.errorParam("名称为空", log);
                return;
            }
            if (vo.getPicUrl() == null) {
                jsonResult.errorParam("图片地址为空", log);
                return;
            }
            if (vo.getFaceValue() == null) {
                jsonResult.errorParam("面额为空", log);
                return;
            }
            if (vo.getQuantity() == null) {
                jsonResult.errorParam("发放总量为空", log);
                return;
            }
            if (vo.getStatus() == null) {
                jsonResult.errorParam("新建现金券状态为空", log);
                return;
            }
            MallCashCoupon mallCashCoupon = mallCashCouponSrvImpl.findOne(vo.getId());
            CashCouponStatus status = mallCashCoupon.getStatus();
            if (status == null || status != CashCouponStatus.WAIT_ISSUE) {
                jsonResult.errorParam("只有草稿状态的现金券才能修改", log);
                return;
            }
            mallCashCoupon.setStatus(CashCouponStatus.valueOf(vo.getStatus()));
            mallCashCoupon.setFaceValue(vo.getFaceValue());
            mallCashCoupon.setQuantity(vo.getQuantity());
            mallCashCoupon.setName(vo.getName());
            mallCashCoupon.setPicUrl(vo.getPicUrl());

            mallCashCoupon = mallCashCouponSrvImpl.update(mallCashCoupon,mallId);

//            Long integrationChannelId = 1l;
//            mallCashCoupon.setIntegrationChannelId(integrationChannelId);
//            mallCashCouponSrvImpl.save(mallCashCoupon, mallId);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /mall/integration/cash/delete M端 删除现金券
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必须参数</code>  现金券id
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_DELETE, method = RequestMethod.PUT)
    @Transactional
    public JsonResult delInfo(@RequestBody MallCashCouponDto vo, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (vo == null) {
                jsonResult.errorParam("现金券信息为空", log);
                return;
            }

            if (vo.getId() == null) {
                jsonResult.errorParam("现金券id为空", log);
                return;
            }
            MallCashCoupon mallCashCoupon = mallCashCouponSrvImpl.findOne(vo.getId());

            CashCouponStatus status = mallCashCoupon.getStatus();
            if (status == null || status != CashCouponStatus.WAIT_ISSUE) {
                jsonResult.errorParam("只有草稿状态的现金券才能删除", log);
                return;
            }
            mallCashCouponSrvImpl.delete(mallCashCoupon);

        };
        return doing.go(request, log);
    }



    /**
     * @api {put} /mall/integration/cash/chg M端 设置现金券的渠道
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必须参数</code>  现金券id
     * @apiParam {Long} integrationChannelId <code>必须参数</code>  积分渠道id
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_CHG, method = RequestMethod.PUT)
    @Transactional
    public JsonResult chgChannel(@RequestBody MallCashCouponDto vo, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (vo == null) {
                jsonResult.errorParam("现金券信息为空", log);
                return;
            }

            if (vo.getId() == null) {
                jsonResult.errorParam("现金券id为空", log);
                return;
            }

            Long integrationChannelId = vo.getIntegrationChannelId();
            if (integrationChannelId == null) {
                jsonResult.errorParam("渠道ID为空", log);
                return;
            }

            IntegrationChannel integrationChannel = integrationChannelRepository.findOne(integrationChannelId);
            if (integrationChannel == null) {
                jsonResult.errorParam("渠道信息不正确", log);
                return;
            }

            MallCashCoupon mallCashCoupon = mallCashCouponSrvImpl.findOne(vo.getId());
            CashCouponStatus status = mallCashCoupon.getStatus();
            if (null == mallCashCoupon) {
                jsonResult.errorParam("没有相应的现金券", log);
                return;
            }
            if (mallCashCoupon.getStatus() == CashCouponStatus.SOLDOUT) {
                jsonResult.errorParam("已停止发放，不能更改渠道", log);
                return;
            }
            if (mallCashCoupon.getIntegrationChannelId() != null) {
                jsonResult.errorParam("已设置渠道，不能更改", log);
                return;
            }
            if (status == null || status != CashCouponStatus.ISSUED) {
                jsonResult.errorParam("只有正在发放的现金券才能更改渠道", log);
                return;
            }

            mallCashCoupon.setIntegrationChannelId(integrationChannelId);
            mallCashCouponSrvImpl.save(mallCashCoupon, mallId);

        };
        return doing.go(request, log);
    }


    /**
     * @api {put} /mall/integration/cash/stop M端 停止发放现金券
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>必须参数</code>  现金券id
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_STOP, method = RequestMethod.PUT)
    @Transactional
    public JsonResult stop(@RequestBody MallCashCouponDto vo, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            MallCashCoupon mallCashCoupon = mallCashCouponSrvImpl.findOne(vo.getId());
            if (null == mallCashCoupon) {
                jsonResult.errorParam("没有相应的现金券", log);
                return;
            }

            if (mallCashCoupon.getStatus() == CashCouponStatus.SOLDOUT) {
                jsonResult.errorParam("已停止发放", log);
                return;
            }

            mallCashCouponSrvImpl.stop(mallCashCoupon, mallId);

        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/cash/page M端 现金券分页查询
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} integrationChannelId <code>可选参数</code>  积分渠道
     * @apiParam {Long} faceValue <code>可选参数</code> 面额
     * @apiParam {String} status <code>必须参数</code> WAIT_ISSUE-草稿，ISSUED-发放中
     * @apiParam {String} startTime <code>可选</code> 开始时间
     * @apiParam {String} endTime <code>可选</code> 结束时间
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":10,
     *                 "name":"积分兑换现金券",
     *                 "dateCreated":"2016-12-27 18:20:35",
     *                 "mallId":51,
     *                 "faceValue":32,
     *                 "quantity":6,
     *                 "status":"ISSUED",
     *                 "integrationChannelId":5,
     *                 "integrationChannelName":"广发证券",
     *                 "exchangeNum":3,
     *                 "receiveNum":2,
     *                 "useNum":1,
     *                 "batchPutNo":"批次号"
     *             },
     *             {
     *                 "id":9,
     *                 "name":"积分兑换现金券",
     *                 "dateCreated":"2016-12-27 18:20:29",
     *                 "mallId":51,
     *                 "faceValue":32,
     *                 "quantity":6,
     *                 "status":"ISSUED",
     *                 "integrationChannelId":5,
     *                 "integrationChannelName":"广发证券",
     *                 "exchangeNum":0,
     *                 "receiveNum":2,
     *                 "useNum":2,
     *                 "batchPutNo":"批次号"
     *             }
     *         ],
     *         "totalCount":2,
     *         "totalPage":1,
     *         "pageNo":0,
     *         "pageSize":10,
     *         "url":"/mall/integration/cash/page",
     *         "prevUrl":"/mall/integration/cash/page?pageNo=0&pageSize=10",
     *         "nextUrl":"/mall/integration/cash/page?pageNo=0&pageSize=10"
     *     }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_PAGE, method = RequestMethod.GET)
    public JsonResult qrCashCouponPage(HttpServletRequest request, MallCashCouponDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(dto.getStatus()) || !EnumUtils.isValidEnum(CashCouponStatus.class, dto.getStatus())) {
                jsonResult.remind("status状态值参数错误",log);
                return;
            }
            Long mallId = userInfoDto.mall.getId();
            PageResult page = this.getPage(dto.getPageNo(), dto.getPageSize());
            PageResult<MallCashCouponDto> pageResult = mallCashCouponSrvImpl.findIntegrationCashCouponPage(mallId, dto, page);

            pageResult.data.stream().map(cashCouponDto -> {

                Long cashCouponId = cashCouponDto.getId();
                Long integrationChannelId = cashCouponDto.getIntegrationChannelId();

                IntegrationCashCouponWallet integrationCashCouponWallet = integrationCashCouponWalletSrv.caculateCash(cashCouponId, integrationChannelId, mallId);

                if (null != integrationCashCouponWallet) {
                    cashCouponDto.setExchangeNum(integrationCashCouponWallet.getExchangeNum());
                    cashCouponDto.setReceiveNum(integrationCashCouponWallet.getReceiveNum());
                    cashCouponDto.setUseNum(integrationCashCouponWallet.getUseNum());
                }

                return cashCouponDto;

            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MALL_INTEGRATION_CASH_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/integration/cash/info M端 现金券详情
     * @apiGroup INTEGRATION_CASH
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Long} id <code>可选参数</code>  现金券id
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         {
     *             "id":10,
     *             "dateCreated":"2016-12-27 18:20:35",
     *             "mallId":51,
     *             "faceValue":32,
     *             "quantity":6,
     *             "status":"ISSUED",
     *             "integrationChannelId":5,
     *             "integrationChannelName":"广发证券",
     *             "exchangeNum":3,
     *             "receiveNum":2,
     *             "useNum":1
     *         }
     *     }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_INTEGRATION_CASH_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request, @RequestParam Long id) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (null == id) {
                jsonResult.remind("id为空",log);
                return;
            }
            MallCashCoupon mallCashCoupon = mallCashCouponSrvImpl.findOne(id);
            jsonResult.data = mallCashCoupon;
        };
        return doing.go(request, log);
    }
}
